import dayjs from 'dayjs'

const beforeExpireTime = 30 * 60 * 1000 // min
const TokenKey = 'token'
const TokenExpireKey = 'token_expire'

// 登录成功后，token一定有值
export function getToken() {
  const token = uni.getStorageSync(TokenKey)
  return token
}

export function setToken(token, expire) {
  uni.setStorageSync(TokenKey, token)
  uni.setStorageSync(TokenExpireKey, expire)
}

export function removeToken() {
  uni.clearStorageSync(TokenKey)
  uni.clearStorageSync(TokenExpireKey)
}

export function needRefreshToken() {
  const hasToken = !!getToken()
  if (hasToken) {
    const currentTime = dayjs(new Date()).unix() * 1000
    const expireTime = dayjs(uni.getStorageSync(TokenExpireKey)).unix() * 1000
    if (currentTime >= expireTime) {
      return false
    }
    return currentTime + beforeExpireTime >= expireTime
  } else {
    return false
  }
}
